<template>
	<view>
		<uni-nav-bar :statusBar="true" dark title="创建联赛" left-icon="left" fixed @clickLeft="clickLeft">
			<block slot="right">
				<!-- <view class="city">
					<view>
						<text class="uni-nav-bar-text" >客服</text>
					</view>
				</view> -->
			</block>
		</uni-nav-bar>
		<view class="content">
			<uni-forms class="form" ref="baseForm" :modelValue="baseFormData" :rules="customRules">
				<uni-forms-item labelWidth="180rpx" label="联赛名称" required name="contestName">
					<uni-easyinput v-model="baseFormData.contestName" placeholder="请输联赛名称" />
				</uni-forms-item>
				<uni-forms-item labelWidth="180rpx" label="地区" required name="area">
					<uni-data-picker v-model="baseFormData.area" :localdata="localData" popup-title="请选择省市区"
						@change="onchange" @nodeclick="onnodeclick">
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item labelWidth="180rpx" label="开始时间" required name="contestBeginTime">
					<uni-datetime-picker v-model="baseFormData.contestBeginTime" type="date" :clear-icon="false">
						<uni-easyinput v-model="baseFormData.contestBeginTime" placeholder="请选开始时间" />
					</uni-datetime-picker>
				</uni-forms-item>
				<uni-forms-item labelWidth="180rpx" label="结束时间" required name="contestEndTime">
					<uni-datetime-picker type="date" :clear-icon="false" v-model="baseFormData.contestEndTime">
						<uni-easyinput v-model="baseFormData.contestEndTime" placeholder="请选结束时间" />
					</uni-datetime-picker>
				</uni-forms-item>
				<uni-forms-item labelWidth="180rpx" label="计分方式" required name="scoringWay">
					<uni-easyinput @focus="onSelected" v-model="scoringList[baseFormData.scoringWay]"
						placeholder="选择计分方式" />
				</uni-forms-item>
				<uni-forms-item labelWidth="180rpx" label="创建人姓名" required name="createUserName">
					<uni-easyinput v-model="baseFormData.createUserName" placeholder="请输入创建人姓名" />
				</uni-forms-item>
				<uni-forms-item labelWidth="180rpx" label="所属机构" required name="organizationId">
					<uni-easyinput @focus="onJumpSelectorganizationId" v-model="tval" placeholder="请输入创建人姓名" />
					<!-- <luyj-select-lay :zindex="9" :value="tval" name="name" placeholder="请选所属机构" :options="datalist"
						@selectitem="selectitem">
					</luyj-select-lay> -->
				</uni-forms-item>
				<uni-forms-item class="topCenter noneboxLine" labelWidth="200px" label="按比赛类型(可多选)" required
					label-position="top" name="competitionType">
					<view class="selectType">
						<view v-for="item in competitionTypeList"
							:class="{cur: selectcompetitionTypeList.includes(item)}" @click="onCompetitionType(item)">
							{{item}}
						</view>

					</view>
				</uni-forms-item>
				<uni-forms-item class="topCenter noneboxLine" labelWidth="200px" label="按联赛类型(可多选)" required
					label-position="top" name="leagueType">
					<view class="selectType">
						<view v-for="item in leagueTypeList" :class="{cur: selectLeagueTypeList.includes(item)}"
							@click="onleagueTypeList(item)">{{item}}</view>
					</view>
				</uni-forms-item>
			</uni-forms>
		</view>

		<view class="bottomBtn">
			<view class="submit-text">
				<checkbox-group @change="onChange">
					<label>
						<checkbox class="chekedBox" active-background-color="#EC7044" color="#FFCC33" checked="true"
							value="cb" />
						<text class="text-grey1">我已阅读并同意 </text>
					</label>
				</checkbox-group><text class="font-color-def">《赛事服务协议》</text>
			</view>
			<button @click="onCreated" type="submit" class="submit" :loading="disabled" :disabled="disabled">
				快速创建
			</button>
		</view>

		<!--  -->
		<uni-popup ref="scoring" type="center">
			<view class="scoring">
				<text v-for="(item,index) in scoringList" @click="onSelectedscoring(index)" :key="index">
					{{item}}</text>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	const cityRows = require('@/plugins/data.json')
	import luyjSelectLay from '@/uni_modules/luyj-select-lay/components/luyj-select-lay/luyj-select-lay.vue'
	import {
		organizationList,
		createdcontest
	} from '@/api/system/user.js'
	export default {
		components: {
			luyjSelectLay
		},
		data() {
			return {
				isOk: 'cb',
				disabled: false,
				back: 1,
				scoringList: ['5v5计分', '3v3计分'],
				competitionTypeList: ['单挑赛', '2v2', '三人篮球', '4v4', '5v5'],
				selectcompetitionTypeList: [],
				leagueTypeList: ['幼儿', '小篮球', '小学', '初中高', '千校联盟', '官方', '社会比赛', '品牌比赛', '大学', '省级联赛', 'U系列', '赛事公司'],
				selectLeagueTypeList: [],
				baseFormData: {
					contestName: '',
					area: '',
					contestBeginTime: '',
					contestEndTime: '',
					createUserName: '',
					organizationId: '',
					leagueType: '',
					competitionType: '',
					scoringWay: ''
				},
				localData: [],
				datalist: [],
				tval: '',
				customRules: {
					area: {
						rules: [{
							required: true,
							errorMessage: '请输选择地区'
						}]
					},
					contestName: {
						rules: [{
							required: true,
							errorMessage: '请输入联赛名称'
						}]
					},
					createUserName: {
						rules: [{
							required: true,
							errorMessage: '请输入创建人姓名'
						}]
					},
					scoringWay: {
						rules: [{
							required: true,
							errorMessage: '请选择计分方式'
						}]
					},
					contestBeginTime: {
						rules: [{
								required: true,
								errorMessage: '请选择开始时间'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									console.log(value, data)
									if (data.contestEndTime && (new Date(data.contestEndTime).getTime() <=
											new Date(value).getTime())) {
										callback('开始时间不能大于结束时间')
									}
									return true
								}
							}
						]
					},
					contestEndTime: {
						rules: [{
								required: true,
								errorMessage: '请选择结束时间'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									console.log(value, data)
									if (data.contestBeginTime && (new Date(data.contestBeginTime).getTime() >=
											new Date(value).getTime())) {
										callback('结束时间不能小于开始时间')
									}
									return true
								}
							}
						]
					},
					organizationId: {
						rules: [{
							required: true,
							errorMessage: '请选择所属机构'
						}]
					},
					leagueType: {
						rules: [{
							required: true,
							errorMessage: '请选择联赛类型'
						}]
					},
					competitionType: {
						rules: [{
							required: true,
							errorMessage: '请选择联赛类型'
						}]
					}
				}
			}
		},
		onReady() {
			this.$refs.baseForm.setRules(this.customRules)
		},
		methods: {
			onJumpSelectorganizationId() {
				uni.navigateTo({
					url: '/pages/mechanism/list?selected=1'
				})
			},
			onChange(val) {
				console.log(val)
				this.isOk = val.detail.value[0]
			},
			// 积分方式
			onSelectedscoring(val) {
				this.baseFormData.scoringWay = val;
				this.$refs.scoring.close();
			},
			// 选择比赛类型
			onCompetitionType(item) {
				console.log(item)
				this.selectcompetitionTypeList.includes(item) ? this.selectcompetitionTypeList.splice(this
					.selectcompetitionTypeList.indexOf(item), 1) : this.selectcompetitionTypeList.push(item);
				this.baseFormData.competitionType = this.selectcompetitionTypeList.join(',')
				console.log(this.selectcompetitionTypeList)
			},
			//联赛类型
			onleagueTypeList(item) {
				this.selectLeagueTypeList.includes(item) ? this.selectLeagueTypeList.splice(this.selectLeagueTypeList
					.indexOf(item), 1) : this.selectLeagueTypeList.push(item);
				this.baseFormData.leagueType = this.selectLeagueTypeList.join(',')
			},
			//  选择
			onSelectorganizationId() {
				console.log(this.$refs.selectorganizationId)
				this.$refs.selectorganizationId.toggleSelector()
			},
			clickLeft() {
				uni.navigateBack()
			},
			onCreated() {

				console.log(this.isOk);
				if (!this.isOk) {
					this.$modal.msg('请先同意《赛事服务协议》')
					return;
				}
				this.disabled = true;

				this.$refs['baseForm'].validate().then(res => {
					console.log('success', res);
					createdcontest(this.baseFormData).then(res => {
						if (this.back) {
							uni.navigateBack();
						} else {
							this.disabled = false;
							uni.navigateTo({
								url: '/pages/season/season'
							})
						}
					}).catch(err => {
						this.disabled = false;
					})

				}).catch(err => {
					this.disabled = false;
				})
				return;
				uni.navigateTo({
					url: '/pages/createCompetition/success'
				})
			},

			// 节点变化后 （并非已经选择完毕）
			onnodeclick(node) {
				// console.log(JSON.stringify(node))
			},

			// 整体选择完成以后
			onchange(e) {
				const value = e.detail.value
				console.log(value)
				let str = ''
				value.forEach(item => {
					str += item.text
				})
				this.baseFormData.area = str
			},



			// 省市区数据树生成
			get_city_tree() {
				let res = []
				if (cityRows.length) {
					// 递归生成
					res = this.handleTree(cityRows)
				}
				return res
			},


			/**
			 * 递归生成树结构数据 - 省市区
			 * 
			 * @param {Object} data
			 * @param {String} parent_code 上级ID | null代表需要顶部菜单
			 * @author Rudon  https://rudon.blog.csdn.net/
			 * 
			 * 源数据：
			 * {
			 * 	  "code": "110100", 
			 *    "name": "北京市",
			 *    "pinyin": "beijingshi",
			 *    "zip_code": "100000",
			 *    "parent_code": "110000",
			 *    "type": 1,
			 *    "first_letter": "B"
			 * }
			 * 
			 * 目标：
			 * {
			 *   text: "XX市",
			 *   value: "810000",
			 *   children: []
			 * }
			 * 
			 */
			handleTree(data, parent_code = null) {
				let res = []

				let keys = {
					id: 'code',
					pid: 'parent_code',
					children: 'children',

					text: 'name',
					value: 'code'
				}

				let oneItemDEMO = {
					text: '',
					value: '',
					children: []
				}
				let oneItem = {}

				// 循环
				for (let index in data) {
					// 判断
					if (parent_code === null) {
						// 顶级菜单 - 省
						if (!data[index].hasOwnProperty(keys.pid) || data[index][keys.pid] == parent_code) {
							// 不存在parent_code，或者已匹配
							oneItem = JSON.parse(JSON.stringify(oneItemDEMO))
							oneItem.text = data[index][keys.text]
							oneItem.value = data[index][keys.value]

							// 递归下去
							oneItem.children = this.handleTree(data, data[index][keys.id])
							res.push(oneItem)

						} else {
							// 匹配不到，跳过
						}

					} else {
						// 非顶级菜单 - 市、区、街道
						if (data[index].hasOwnProperty(keys.pid) && data[index][keys.pid] == parent_code) {
							// 已匹配
							oneItem = JSON.parse(JSON.stringify(oneItemDEMO))
							oneItem.text = data[index][keys.text]
							oneItem.value = data[index][keys.value]

							// 递归下去
							oneItem.children = this.handleTree(data, data[index][keys.id])
							res.push(oneItem)

						} else {
							// 匹配不到，跳过
						}

					}

				}

				return res
			},
			onSelected() {
				this.$refs.scoring.open();
			}
		},
		onLoad({
			back
		}) {
			this.back = back
			// 省市区数据树生成
			this.localData = this.get_city_tree()

			organizationList().then(res => {
				let list = []
				res.rows.forEach(item => {

					list.push({
						label: item.name,
						value: item.id
					})
				})
				console.log(list);
				this.datalist = list;
			})
			// console.log(JSON.stringify(this.localData))
		},
		onShow() {
			console.log('1')
			let data = uni.getStorageSync('organizationData')
			console.log(data);
			this.tval = data.name;
			this.baseFormData.organizationId = data.id;
		},
		onHide() {
			console.log('hide')
		}

	}
</script>

<style scoped lang="scss">
	body {
		background-color: #fff !important;
	}

	.content {
		padding: 40rpx 20rpx;
	}

	.scoring {
		padding: 30rpx 60rpx;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		border-radius: 20rpx;

		text {
			&:nth-child(1) {
				border-bottom: 1px solid #ddd;
				padding: 30rpx 0;
			}

			&:nth-child(2) {
				padding: 30rpx 0;

				text {
					border: none;
					margin-left: 10rpx;
					color: #aeadad;
				}
			}
		}
	}

	.topCenter {
		flex-direction: column !important;
	}

	.selectType {
		display: flex;
		flex-wrap: wrap;
		margin-top: 20rpx;

		view {
			display: flex;
			align-items: center;
			padding: 10rpx 20rpx;
			background: #ddd;
			margin-right: 20rpx;
			margin-bottom: 20rpx;

			&.cur {
				background-color: $btn-bg-color;
				color: #fff;
			}
		}
	}

	.bottomBtn {
		display: flex;
		justify-content: center;
		flex-direction: column;
		background-color: #fff;
		position: sticky;
		bottom: 0;
		padding: 40rpx 30rpx;
		padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
		border-top: 1px solid #eee;

		.submit-text {
			display: flex;

			font-size: 24rpx;
		}

		.submit {
			background-color: $btn-bg-color;
			color: #fff;
			width: 100%;
			font-size: 34rpx;
			font-weight: 800;
			margin-top: 20rpx;
		}

		::v-deep uni-checkbox-group {
			display: inline-block;

		}

		.chekedBox {
			margin-right: 10px;

			::v-deep.uni-checkbox-input {
				border-radius: 100%;
			}

			&::before {
				font-size: 12px;
				right: 3px;
			}

			::v-deep.uni-checkbox-input {
				width: 16px;
				height: 16px;
			}
		}
	}
</style>